$(function() {
    var str = localStorage.getItem("users");
    var usersLocal = JSON.parse(str);
    var code = "";
    // 创建验证码
    function createCode() {
        newCode = "";
        var codeLength = 4;
        var oldCoed = $("#codeto").get(0);
        var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
        for (var i = 0; i < codeLength; i++) {
            var index = parseInt(Math.random() * 62)
            newCode += random[index];
        }
        oldCoed.value = newCode;
        code = oldCoed.value;
    }
    // 点击验证码,产生随机的验证码数字
    $("#codeto").click(function() {
        createCode();
    });
    var usernames = [];
    var passwords = [];
    for (let i = 0; i < usersLocal.length; i++) {
        usernames.push(usersLocal[i].username);
        passwords.push(usersLocal[i].password);
    }


    //验证的Demo
    layui.use('form', function() {
        var form = layui.form;
        // 自定义比较规则
        var username = "";
        form.verify({
                username: function(value) {
                    username = value;
                    if (usernames.indexOf(value) < 0) {
                        return "用户名不存在";
                    } else {
                        return;
                    }
                },
                password: function(value) {
                    var usernameIndex = usernames.indexOf(username);
                    if (value != passwords[usernameIndex]) {
                        return "密码不正确"
                    }
                },
                code: function(value) {
                    if (value != code) {
                        return '验证码输入不正确';
                    }
                }
            })
            //监听提交
        form.on('submit(formDemo)', function(data) {
            // 设置当前登录的用户
            var loginLocal = $("input[name=username]").val();
            localStorage.setItem("LoginLocal", loginLocal);
            return true;
        });
    });
});